package com.sikaryofficial.backend.manager;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sikaryofficial.backend.config.TenantFilterProperties;
import com.sikaryofficial.backend.domain.dto.req.brandspecial.BrandSpecialReq;
import com.sikaryofficial.backend.domain.dto.resp.brandspecial.BrandSpecialDTO;
import com.sikaryofficial.backend.domain.entity.BrandSpecial;
import com.sikaryofficial.backend.domain.mapping.BrandSpecialMapping;
import com.sikaryofficial.backend.service.IAttachmentService;
import com.sikaryofficial.backend.service.IBrandSpecialService;
import com.sikaryofficial.backend.service.article.cache.ReceivedLikesCacheService;
import com.sikaryofficial.backend.service.brandspecial.cache.BrandSpecialCacheService;
import com.sikaryofficial.backend.service.follow.cache.FollowCacheService;
import com.sikaryofficial.backend.service.user.UserCacheService;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.system.api.model.att.AttachmentResp;
import com.sikaryofficial.system.api.model.infomation.FollowCountVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author : qinjinyuan
 * @desc : 品牌专栏服务
 * @date : 2023/10/30 15:39
 */
@Service
@Slf4j
public class BrandSpecialManager {
    @Autowired
    private IBrandSpecialService brandSpecialService;
    @Autowired
    private TenantFilterProperties tenantFilterProperties;
    @Autowired
    private UserCacheService userCacheService;
    @Autowired
    private FollowCacheService followCacheService;
    @Autowired
    private ReceivedLikesCacheService receivedLikesCacheService;
    @Autowired
    private IAttachmentService attachmentService;
    @Autowired
    private BrandSpecialCacheService brandSpecialCacheService;

    /**
     * 品牌专栏表信息保存
     *
     * @param attachmentList
     * @param brandSpecialId
     */
    private void saveAttachment(List<AttachmentResp> attachmentList, Long brandSpecialId) {
        // 删除原有附件
        attachmentService.deleteAttachmentList(brandSpecialId, SecurityUtils.getUserId());
        // 保存附件信息
        attachmentService.saveAttachmentList(brandSpecialId, attachmentList, SecurityUtils.getUserId());
    }

    private void processOtherInfo(Long authorId, BrandSpecialDTO item, Long currentUserId) {
        if (Objects.isNull(authorId)) {
            return;
        }
        // 用户到的关注数量 (粉丝数量)
        FollowCountVO followCountVO = followCacheService.getFollowCount(authorId);
        item.setFansCount(Objects.nonNull(followCountVO.getFansCount()) ? followCountVO.getFansCount() : 0L);
        item.setFollowCount(Objects.nonNull(followCountVO.getFriendCount()) ? followCountVO.getFriendCount() : 0L);
        // 查看当前用户是否关注文章作者
        item.setHasFollow(followCacheService.hasFollow(currentUserId,authorId));
    }

    private void buildAttachments(BrandSpecialDTO brandSpecialDTO) {
        brandSpecialDTO.setAttachmentList(getAttachmentById(brandSpecialDTO.getBrandSpecialId()));
    }

    private List<AttachmentResp> getAttachmentById(Long articleId) {
        return attachmentService.getAttachmentDescById(articleId);
    }

    /**
     * 列表
     *
     * @return
     */
    public List<BrandSpecialDTO> list() {
        return brandSpecialCacheService.getAllBrandSpecialList();
    }

    /**
     * 详情
     *
     * @param brandSpecialId
     * @return
     */
    public BrandSpecialDTO getInfo(Long brandSpecialId) {
        BrandSpecial brandSpecial = brandSpecialService.getOne(new LambdaQueryWrapper<BrandSpecial>()
                .eq(BrandSpecial::getBrandSpecialId, brandSpecialId)
                .eq(BrandSpecial::getDeletedVersion, 0L)
        );
        if (Objects.isNull(brandSpecial)) {
            throw new ServiceException("Brand Special not exists");
        }
        BrandSpecialDTO brandSpecialDTO = BrandSpecialMapping.INSTANCE.coverToDTO(brandSpecial);
        // 附件信息
        buildAttachments(brandSpecialDTO);
        return brandSpecialDTO;
    }

    /**
     * 详情
     *
     * @param brandSpecialId
     * @return
     */
    public BrandSpecialDTO detail(Long brandSpecialId) {
        BrandSpecialDTO brandSpecialDTO = getInfo(brandSpecialId);
        processOtherInfo(brandSpecialDTO.getAuthorId(), brandSpecialDTO, SecurityUtils.getUserId());
        return brandSpecialDTO;
    }

    /**
     * 数据保存
     *
     * @param req
     * @return
     */
    public Long saveOrUpdate(BrandSpecialReq req) {
        Integer tenantId = tenantFilterProperties.getTenantByBrand(req.getBrandNo());
        if(Objects.isNull(tenantId)){
            log.error("不支持创建该品牌专栏");
            return 0L;
        }
        BrandSpecial brandSpecial = BrandSpecialMapping.INSTANCE.coverReqToEntity(req);
        brandSpecial.setTenantId(tenantId);
        brandSpecial.setAuthorId(Objects.isNull(tenantId) ? 0L : Long.parseLong(tenantId.toString()));
        if (Objects.isNull(req.getBrandSpecialId())) {
            brandSpecial.setCreatedBy(SecurityUtils.getUserId());
            brandSpecial.setCreatedTime(new Date());
            brandSpecialService.save(brandSpecial);
        } else {
            brandSpecial.setUpdatedBy(SecurityUtils.getUserId());
            brandSpecial.setUpdatedTime(new Date());
            brandSpecialService.updateById(brandSpecial);
        }
        Long brandSpecialId = brandSpecial.getBrandSpecialId();
        // 保存附件
        saveAttachment(req.getAttachmentList(), brandSpecialId);
        // 清除缓存
        brandSpecialCacheService.remove();
        return brandSpecial.getBrandSpecialId();
    }

    /**
     * 删除
     *
     * @param brandSpecialIds
     * @return
     */
    public Boolean remove(String brandSpecialIds) {
        if (CharSequenceUtil.isBlank(brandSpecialIds)) {
            return false;
        }
        String[] brandSpecialIdStirs = brandSpecialIds.split(",");
        for (String brandSpecialIdStr : brandSpecialIdStirs) {
            Long brandSpecialId = Long.parseLong(brandSpecialIdStr);
            BrandSpecial brandSpecial = brandSpecialService.getOne(new LambdaQueryWrapper<BrandSpecial>()
                    .eq(BrandSpecial::getBrandSpecialId, brandSpecialId)
                    .eq(BrandSpecial::getDeletedVersion, 0L)
            );
            if (Objects.isNull(brandSpecial)) {
                continue;
            }
            brandSpecialService.update(new LambdaUpdateWrapper<BrandSpecial>()
                    .setSql(" deleted_version = brand_special_id ")
                    .set(BrandSpecial::getUpdatedBy, SecurityUtils.getUserId())
                    .set(BrandSpecial::getUpdatedTime, new Date())
                    .eq(BrandSpecial::getBrandSpecialId, brandSpecialId)
                    .eq(BrandSpecial::getDeletedVersion, 0L)
            );
        }
        // 清除缓存
        brandSpecialCacheService.remove();
        return true;
    }
}
